package com.ruoyi.kanban.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.kanban.domain.KanbanOrder;
import com.ruoyi.kanban.mapper.KanbanOrderMapper;
import com.ruoyi.kanban.service.IKanbanOrderService;

/**
 * 看板订单Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-01-18
 */
@Service
public class KanbanOrderServiceImpl extends ServiceImpl<KanbanOrderMapper, KanbanOrder>
        implements IKanbanOrderService {

    @Autowired
    private KanbanOrderMapper kanbanOrderMapper;

    /**
     * 查询看板订单列表
     * 
     * @param kanbanOrder 看板订单
     * @return 看板订单
     */
    @Override
    public List<KanbanOrder> selectKanbanOrderList(KanbanOrder kanbanOrder) {
        LambdaQueryWrapper<KanbanOrder> wrapper = buildWrapper(kanbanOrder);
        return this.list(wrapper);
    }

    /**
     * 查询看板订单详细信息
     * 
     * @param id 看板订单主键
     * @return 看板订单
     */
    @Override
    public KanbanOrder selectKanbanOrderById(Long id) {
        return this.getById(id);
    }

    /**
     * 根据看板编码查询看板订单
     * 
     * @param kanbanCode 看板编码
     * @return 看板订单
     */
    @Override
    public KanbanOrder selectKanbanOrderByCode(String kanbanCode) {
        return kanbanOrderMapper.selectKanbanOrderByCode(kanbanCode);
    }

    /**
     * 新增看板订单
     * 
     * @param kanbanOrder 看板订单
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertKanbanOrder(KanbanOrder kanbanOrder) {
        kanbanOrder.setCreateBy(SecurityUtils.getUsername());
        kanbanOrder.setCreateTime(new Date());
        return this.save(kanbanOrder);
    }

    /**
     * 修改看板订单
     * 
     * @param kanbanOrder 看板订单
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateKanbanOrder(KanbanOrder kanbanOrder) {
        kanbanOrder.setUpdateBy(SecurityUtils.getUsername());
        kanbanOrder.setUpdateTime(new Date());
        return this.updateById(kanbanOrder);
    }

    /**
     * 批量删除看板订单
     * 
     * @param ids 需要删除的看板订单主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteKanbanOrderByIds(List<Long> ids) {
        return this.removeByIds(ids);
    }

    /**
     * 删除看板订单信息
     * 
     * @param id 看板订单主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteKanbanOrderById(Long id) {
        return this.removeById(id);
    }

    /**
     * 根据框架协议ID查询看板订单列表
     * 
     * @param frameworkId 框架协议ID
     * @return 看板订单集合
     */
    @Override
    public List<KanbanOrder> selectKanbanOrderByFrameworkId(Long frameworkId) {
        return kanbanOrderMapper.selectKanbanOrderByFrameworkId(frameworkId);
    }

    /**
     * 根据业务状态查询看板订单列表
     * 
     * @param businessStatus 业务状态
     * @return 看板订单集合
     */
    @Override
    public List<KanbanOrder> selectKanbanOrderByStatus(Integer businessStatus) {
        return kanbanOrderMapper.selectKanbanOrderByStatus(businessStatus);
    }

    /**
     * 统计看板订单数量
     * 
     * @param params 查询参数
     * @return 统计结果
     */
    @Override
    public Map<String, Object> selectKanbanOrderStatistics(Map<String, Object> params) {
        return kanbanOrderMapper.selectKanbanOrderStatistics(params);
    }

    /**
     * 批量更新看板订单状态
     * 
     * @param ids 订单ID列表
     * @param businessStatus 业务状态
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateKanbanOrderStatusBatch(List<Long> ids, Integer businessStatus) {
        String updateBy = SecurityUtils.getUsername();
        int result = kanbanOrderMapper.updateKanbanOrderStatusBatch(ids, businessStatus, updateBy);
        return result > 0;
    }

    /**
     * 发货方确认看板订单
     * 
     * @param id 看板订单ID
     * @param confirmRemark 确认备注
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean confirmKanbanOrderBySender(Long id, String confirmRemark) {
        KanbanOrder kanbanOrder = new KanbanOrder();
        kanbanOrder.setId(id);
        kanbanOrder.setSenderConfirmStatus(1); // 已确认
        kanbanOrder.setSenderConfirmTime(new Date());
        kanbanOrder.setSenderConfirmUser(SecurityUtils.getUsername());
        kanbanOrder.setSenderConfirmRemark(confirmRemark);
        kanbanOrder.setUpdateBy(SecurityUtils.getUsername());
        kanbanOrder.setUpdateTime(new Date());
        return this.updateById(kanbanOrder);
    }

    /**
     * 打印箱标
     * 
     * @param id 看板订单ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean printBoxLabel(Long id) {
        KanbanOrder kanbanOrder = this.getById(id);
        if (kanbanOrder == null) {
            return false;
        }
        
        kanbanOrder.setBoxLabelPrinted(1); // 已打印
        kanbanOrder.setBoxLabelPrintTime(new Date());
        kanbanOrder.setBoxLabelPrintCount(
            kanbanOrder.getBoxLabelPrintCount() == null ? 1 : kanbanOrder.getBoxLabelPrintCount() + 1);
        kanbanOrder.setUpdateBy(SecurityUtils.getUsername());
        kanbanOrder.setUpdateTime(new Date());
        return this.updateById(kanbanOrder);
    }

    /**
     * 打印看板
     * 
     * @param id 看板订单ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean printKanban(Long id) {
        KanbanOrder kanbanOrder = this.getById(id);
        if (kanbanOrder == null) {
            return false;
        }
        
        kanbanOrder.setKanbanPrinted(1); // 已打印
        kanbanOrder.setKanbanPrintTime(new Date());
        kanbanOrder.setKanbanPrintCount(
            kanbanOrder.getKanbanPrintCount() == null ? 1 : kanbanOrder.getKanbanPrintCount() + 1);
        kanbanOrder.setUpdateBy(SecurityUtils.getUsername());
        kanbanOrder.setUpdateTime(new Date());
        return this.updateById(kanbanOrder);
    }

    /**
     * 构建查询条件
     * 
     * @param kanbanOrder 查询条件
     * @return 查询包装器
     */
    private LambdaQueryWrapper<KanbanOrder> buildWrapper(KanbanOrder kanbanOrder) {
        LambdaQueryWrapper<KanbanOrder> wrapper = new LambdaQueryWrapper<>();
        
        wrapper.like(StringUtils.isNotEmpty(kanbanOrder.getKanbanCode()), 
                    KanbanOrder::getKanbanCode, kanbanOrder.getKanbanCode())
               .eq(kanbanOrder.getFrameworkId() != null, 
                   KanbanOrder::getFrameworkId, kanbanOrder.getFrameworkId())
               .like(StringUtils.isNotEmpty(kanbanOrder.getFrameworkCode()), 
                     KanbanOrder::getFrameworkCode, kanbanOrder.getFrameworkCode())
               .eq(kanbanOrder.getReceiverCompanyId() != null, 
                   KanbanOrder::getReceiverCompanyId, kanbanOrder.getReceiverCompanyId())
               .like(StringUtils.isNotEmpty(kanbanOrder.getReceiverCompanyName()), 
                     KanbanOrder::getReceiverCompanyName, kanbanOrder.getReceiverCompanyName())
               .eq(kanbanOrder.getSenderCompanyId() != null, 
                   KanbanOrder::getSenderCompanyId, kanbanOrder.getSenderCompanyId())
               .like(StringUtils.isNotEmpty(kanbanOrder.getSenderCompanyName()), 
                     KanbanOrder::getSenderCompanyName, kanbanOrder.getSenderCompanyName())
               .like(StringUtils.isNotEmpty(kanbanOrder.getMaterialCode()), 
                     KanbanOrder::getMaterialCode, kanbanOrder.getMaterialCode())
               .like(StringUtils.isNotEmpty(kanbanOrder.getMaterialName()), 
                     KanbanOrder::getMaterialName, kanbanOrder.getMaterialName())
               .eq(kanbanOrder.getBusinessStatus() != null, 
                   KanbanOrder::getBusinessStatus, kanbanOrder.getBusinessStatus())
               .eq(kanbanOrder.getSenderConfirmStatus() != null, 
                   KanbanOrder::getSenderConfirmStatus, kanbanOrder.getSenderConfirmStatus())
               .eq(KanbanOrder::getDelFlag, 0); // 未删除
        
        // 处理时间参数
        if (kanbanOrder.getParams() != null) {
            Map<String, Object> params = kanbanOrder.getParams();
            
            // 创建时间筛选
            if (params.get("beginCreateTime") != null) {
                wrapper.ge(KanbanOrder::getCreateTime, params.get("beginCreateTime"));
            }
            if (params.get("endCreateTime") != null) {
                wrapper.le(KanbanOrder::getCreateTime, params.get("endCreateTime"));
            }
            
            // 要求到货时间筛选
            if (params.get("beginRequiredDeliveryTime") != null) {
                wrapper.ge(KanbanOrder::getRequiredDeliveryTime, params.get("beginRequiredDeliveryTime"));
            }
            if (params.get("endRequiredDeliveryTime") != null) {
                wrapper.le(KanbanOrder::getRequiredDeliveryTime, params.get("endRequiredDeliveryTime"));
            }
        }
        
        // 按创建时间倒序
        wrapper.orderByDesc(KanbanOrder::getCreateTime);
        
        return wrapper;
    }
}